package com.itheima.dao.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private ComboPooledDataSource dataSource = new ComboPooledDataSource("c3p0-config.xml");
    private QueryRunner qr = new QueryRunner(dataSource);

    @Override
    public boolean Register(User user) throws SQLException {
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?)";
        int i = qr.update(sql, null, user.getName(), user.getGender(), user.getAge()
                , user.getAddress(), user.getQq(), user.getEmail(),
                user.getUsername(), user.getPassword());

        return i == 0 ? false : true;
    }

    @Override
    public User login(User user) throws SQLException {

        String sql = "select * from  user where username=? and password=?";
        User user1 = qr.query(sql, new BeanHandler<User>(User.class), user.getUsername(), user.getPassword());
        return user1;
    }

    @Override
    public List<User> findAllUser() throws SQLException {
        String sql = "select * from user";
        return qr.query(sql, new BeanListHandler<User>(User.class));
    }

    @Override
    public boolean addUser(User user) throws SQLException {
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?)";
        int i = qr.update(sql, null, user.getName(), user.getGender(), user.getAge()
                , user.getAddress(), user.getQq(), user.getEmail(),
                user.getUsername(), user.getPassword());

        return i == 0 ? false : true;
    }

    @Override
    public User findById(String id) throws SQLException {
        String sql="select * from user where id=?";
        return qr.query(sql,new BeanHandler<User>(User.class),id);
    }

    @Override
    public boolean update(User user) throws SQLException {
        String sql="update user set  gender=?,age=?,address=?,qq=?,email=? where name=?";
        int i = qr.update(sql, user.getGender(),
                user.getAge(), user.getAddress(), user.getQq(),
                user.getEmail(), user.getName());
        return i==0?false:true;
    }

    @Override
    public boolean deleteById(String id) throws SQLException {
        String sql="delete from user where id=?";
        int update = qr.update(sql, id);
        return update==0?false:true;
    }

}
